package model;

import java.io.File;
import java.io.IOException;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
 * XLS reader, uses the XLSReader open-source class library
 * @author Audun
 *
 */

public class XLSReader {
	private Workbook workbook;
	private Sheet sheet;
	private Cell[] row;
	private Cell[] column;
	private String workbookToRead;

	public XLSReader(String workbookToRead) {
		this.workbookToRead = workbookToRead;
		initComponents();
	}
	
	/**
	 * Initializes workbook and sheet components in order to read from the "database"
	 */
	public void initComponents() {
		try {
			workbook = Workbook.getWorkbook(new File(workbookToRead));
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sheet = workbook.getSheet(0);
	}
	
	/**
	 * Figures out the length of the row
	 * @param rowNumber
	 * @return
	 */
	public int getRowArraySize(int rowNumber) {
		int arraySize = sheet.getColumnView(rowNumber).getSize();
		return arraySize;
	}
	
	/**
	 * Figures out the length of the column
	 * @param columnNumber
	 * @return
	 */
	public int getColumArraysize(int columnNumber) {
		int arraySize = sheet.getRowView(columnNumber).getSize();
		return arraySize;
	}
	
	/**
	 * Returns a row in a cell array
	 * @param rowNumber
	 * @return
	 */
	public Cell[] getRowArray(int rowNumber) {
		row = sheet.getRow(rowNumber);
		return row;
		}
	
	/**
	 * Returns a column in a cell array
	 * @param columnNumber
	 * @return
	 */
	public Cell[] getColumnArray(int columnNumber) {
		column = new Cell[getColumArraysize(columnNumber)];
		column = sheet.getColumn(columnNumber);
		return column;
	}
	
	/**
	 * Converts an array of type cell to an array of type string
	 * @param array
	 * @return
	 */
	public String[] convertCellArraytoStringArray(Cell[] array) {
		String[] convertedArray = new String[array.length];
		for (int i = 0; i < array.length; i++) {
			if(array[i].getContents().trim().isEmpty()) {
				convertedArray[i] = "n/e";
			}
			else if(array[i].getContents().trim().contentEquals(".")) {
				convertedArray[i] = "n/e";
			}
			else {
			convertedArray[i] = array[i].getContents();
		}
		}
		return convertedArray;
	}

}
